import com.dao.UserDao;
import com.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class MyBatisCRUD {

    SqlSessionFactory factory;
    SqlSession sqlSession;

    //封装
    @Before
    public void init() throws IOException {
        //1.获得读取MyBatis配置文件的流对象
        InputStream is = Resources.getResourceAsStream("mybatis-config.xml");

        //2.构建SqlSession连接对象的工厂
        factory = new SqlSessionFactoryBuilder().build(is);
    }
    //查找全部
    @Test
    public void findAll() throws IOException {
        //3.通过工厂获得连接对象
        SqlSession sqlSession = factory.openSession();
        //4.通过连接对象获得接口实现类对象
        UserDao userDao = sqlSession.getMapper(UserDao.class);

        List<User> userList = userDao.findAll();
        for (User user : userList) {
            //5.调用接口中的方法
            System.out.println(user);
        }
    }

    //通过id查找
    @Test
    public void findById() {

        SqlSession sqlSession = factory.openSession();

        UserDao userDao = sqlSession.getMapper(UserDao.class);

        User user = userDao.findById(2);

        System.out.println(user);
    }

    //删除
    public void deleteById(){

        SqlSession sqlSession = factory.openSession();

        UserDao userDao = sqlSession.getMapper(UserDao.class);

        boolean delete = userDao.deleteById(2);

        System.out.println(delete);
        //提交
        sqlSession.commit();

    }

    //修改
    @Test
    public void update(){

        SqlSession sqlSession = factory.openSession();

        UserDao userDao = sqlSession.getMapper(UserDao.class);

        User user = new User();
        user.setId(3);
        user.setName("佳伟");
        user.setAge(18);

        int update = userDao.update(user);

        System.out.println(update);
        //提交
        sqlSession.commit();
    }

    //添加
    @Test
    public void add(){

        SqlSession sqlSession = factory.openSession();

        UserDao userDao = sqlSession.getMapper(UserDao.class);

        User user = new User();
        user.setName("王宸");
        user.setAge(20);

        userDao.add(user);

        //提交
        sqlSession.commit();

        //???
        System.out.println(user.getId());
    }

    @After
    public void close(){
        sqlSession.close();
    }
}
